package com.android.goal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Utility {	
	
	final static String host = "http://10.0.2.2:8888/";
	
	public static void setListViewStatic(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
	
	public static String getHttp(String link){
		BufferedReader in = null;        
        try {
        	HttpClient client = new DefaultHttpClient();        
        	HttpGet request = new HttpGet();
        	request.setURI(new URI(link));
        	
        	HttpResponse response = client.execute(request);
        	// Luu response vao buffer
        	in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
        	
        	StringBuffer sb = new StringBuffer("");
        	String line = "";
        	String NL = System.getProperty("line.separator");
        	// Doc tung dong vao string buffer
        	while ((line = in.readLine()) != null) {
        		sb.append(line + NL);
        	}       
        	in.close();        	
        	String page = sb.toString();        	  	
        	return page;        	
        } catch (IOException e) {
        	e.printStackTrace();
        } catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}        			
	    return ""; 
	}
	
	public static String getHttpMatch(String date){
		String link = host + "matches?method=GetListOfMatch&date=" + date + "&IDLeague=";
		return getHttp(link);
	}
}
